//
// Created by martics on 24-9-5.
//
#include "tools.h"

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


void sys_err(const char* msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

void set_container_hostname(const char* hostname) {
    if (sethostname(hostname, strlen(hostname)) == -1) {
        sys_err("set hostname error!");
    }
}

void write_file(const char* filename, const char* content) {
    const int fd = open(filename, O_WRONLY);
    if (-1 == fd) {
        char err_msg[strlen(filename) + 20];
        sprintf(err_msg, "open file %s error", filename);
        perror(err_msg);
        exit(EXIT_FAILURE);
    }

    if (-1 == write(fd, content, strlen(content))) {
        char err_msg[strlen(filename) + strlen(content) + 25];
        sprintf(err_msg, "write '%s' to file:%s error", content, filename);
        perror(err_msg);
        exit(EXIT_FAILURE);
    }

    close(fd);
}

void ensure_directory_exists(const char *path) {
    struct stat info;

    if (stat(path, &info) != 0) {
        if (errno == ENOENT) {
            if (mkdir(path, 0755) == 0) {
                printf("create dir success: %s\n", path);
                return;
            }

            perror("目录创建失败");
            exit(EXIT_FAILURE);
        }
        perror("stat 错误");
        exit(EXIT_FAILURE);
    }

    if (info.st_mode & S_IFDIR) {
        printf("dir exist: %s\n", path);
        return;
    }

    fprintf(stderr, "路径存在但不是目录: %s\n", path);
}
